package top.saodisheng.proxy.demo;

import top.saodisheng.proxy.DefaultEchoService;
import top.saodisheng.proxy.EchoService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK 动态代理
 * 基于接口代理，通过反射机制生成一个实现代理接口的类，在调用具体方法时会调用 InvokeHandler 来处理。
 * @author saodisheng
 * @date 2021/9/13
 */
public class JdkDynamicProxyDemo {

	public static void main(String[] args) {
		// 当前线程的类加载器
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		// $Proxy0
		Object proxy = Proxy.newProxyInstance(classLoader, new Class[]{EchoService.class}, new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				if (EchoService.class.isAssignableFrom(method.getDeclaringClass())) {
					// 被代理对象
					EchoService echoService = new DefaultEchoService();
					long startTime = System.currentTimeMillis();
					String result = echoService.echo((String) args[0]);
					long costTime = System.currentTimeMillis() - startTime;
					System.out.println("echo 方法执行的实现：" + costTime + " ms.");
					return result;
				}
				return null;
			}
		});
		EchoService echoService = (EchoService) proxy;
		echoService.echo("Hello,World");
	}
}

